package db

import (
	"fmt"
	_"github.com/go-sql-driver/mysql"
	"github.com/jmoiron/sqlx"
    "sync"
)

// 单例模式
var instance *sqlx.DB
var once sync.Once
var err string

type DbInfo struct {
    Engine string	`json:"engine"`
    User   string	`json:"user"`
    Password   string	`json:"password"`
    Host     string	 `json:"host"`
    Port   string	`json:"port"`
    Dbname  string  `json:"dbname"`
}

type Person struct {
	Username string
	Age int
}

func _init (dbinfo DbInfo) (database *sqlx.DB, errorMsg string){
    fmt.Println("数据连接信息", dbinfo)
    database, err := sqlx.Open(dbinfo.Engine, fmt.Sprintf("%s:%s@tcp(%s:%s)/%s", dbinfo.User, dbinfo.Password, dbinfo.Host, dbinfo.Port, dbinfo.Dbname))
    if err != nil {
        errorMsg = "mysql open failed, error:" + err.Error()
        fmt.Println(errorMsg)
    }
    return database,errorMsg
}

func ConnectMysql(dbinfo DbInfo) *sqlx.DB {
    once.Do(func() {
        instance,err = _init(dbinfo)
    })
    return instance
}

